<template>
  <div class="product-share">
    <canvas type="2d" id="myCanvas" :hidden="false"></canvas>
    <div class="footer-box">
      <cover-view class="main">
        <button class="btn direct" open-type="share">直接分享</button>
        <button class="btn" @click="toSaveImage">海报分享</button>
      </cover-view>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Share from "@/common/share";
var canvas;
export default {
  components: {},
  data() {
    return {
      shareInfo: {},
      sharePath: "",
      shareCode: "",
      qrCodeUrl: "",
      logUrl: "https://media.wxcwy.com/mini/images/logo@2x.png",
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  onLoad(options) {
    this.shareInfo = JSON.parse(decodeURIComponent(options.shareInfo));
    Share.shareCode = this.shareInfo.share_code;
  },
  async onReady() {
    if (this.shareInfo.id) {
      await this.getShareProductCode();
      this.getCavas();
    }
  },
  onShareAppMessage(res) {
    let { id, share_title, share_picture, title } = this.shareInfo;
    let shareTitle = share_title || title;
    return Share.getShareId({
      id,
      from: res.from,
      shareLink: `shop/productDetails/productDetails`,
      shareTitle,
      shareImgUrl: share_picture,
    });
  },
  methods: {
    getShareProductCode() {
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      let { id, share_code } = this.shareInfo;
      return this.$api
        .getShareProductCode({
          product_id: id,
          share_code: share_code,
          page: "shop/productDetails/productDetails",
        })
        .then((res) => {
          if (res.code == 200) {
            this.qrCodeUrl = res.data.url;
            return res.data.url;
          }
        });
    },
    getCavas() {
      const query = wx.createSelectorQuery();
      query
        .select("#myCanvas")
        .fields({ node: true, size: true })
        .exec((res) => {
          canvas = res[0].node;
          const ctx = canvas.getContext("2d");
          const { pixelRatio, screenWidth } = wx.getSystemInfoSync();
          const dpr = 2;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
          //绘制背景色
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, screenWidth, canvas.height);

          //绘制内容

          this.toDrawCanvas(ctx, screenWidth);
          uni.hideLoading();
        });
    },
    async toDrawCanvas(ctx, imgW) {
      const posterH = uni.upx2px(1260);
      const posterImg = await this.loadImage(this.shareInfo.share_picture);

      ctx.drawImage(posterImg, 0, 0, imgW, posterH);

      //绘制透明背景
      ctx.save();
      ctx.globalAlpha = 0.7;
      ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, imgW, uni.upx2px(68));
      ctx.fillRect(0, posterH - uni.upx2px(140), imgW, uni.upx2px(140));
      ctx.restore();

      setTimeout(() => {
        this.toDrawQrCode(ctx, 0, posterH);
        this.toDrawAvaer(ctx, imgW);
        this.toDrawText(ctx, posterH, imgW);
      }, 0);
    },
    async toDrawQrCode(ctx, x, y) {
      const qrCodeImg = await this.loadImage(this.qrCodeUrl);
      const avatarImg = await this.loadImage(this.userInfo.avatar);
      const avatarImgW = uni.upx2px(82);
      ctx.drawImage(
        qrCodeImg,
        x + uni.upx2px(46),
        y - uni.upx2px(200),
        uni.upx2px(180),
        uni.upx2px(180)
      );

      ctx.save();
      ctx.beginPath(); //开始绘制
      ctx.arc(
        x + uni.upx2px(136),
        y - uni.upx2px(110),
        avatarImgW / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.clip();
      ctx.drawImage(
        avatarImg,
        x + uni.upx2px(136) - avatarImgW / 2,
        y - uni.upx2px(110) - avatarImgW / 2,
        avatarImgW,
        avatarImgW
      );
      ctx.restore();
    },
    async toDrawAvaer(ctx, imgW) {
      const avatarH = uni.upx2px(48);
      const avaerImg = await this.loadImage(this.logUrl);
      ctx.save();
      ctx.beginPath(); //开始绘制
      ctx.arc(
        avatarH / 2 + uni.upx2px(200),
        avatarH / 2 + uni.upx2px(10),
        avatarH / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.clip();
      ctx.drawImage(
        avaerImg,
        uni.upx2px(200),
        uni.upx2px(10),
        avatarH,
        avatarH
      );
      ctx.restore();
    },
    toDrawText(ctx, y, screenWidth) {
      const padding = uni.upx2px(40);
      ctx.textAlign = "center";
      ctx.font = `${uni.upx2px(28)}px Arial`;
      ctx.fillStyle = "#ffffff";

      ctx.fillText(
        "每一刻都是美丽时光",
        screenWidth / 2 + uni.upx2px(40),
        uni.upx2px(46),
        screenWidth
      );
      let splitChar = "";
      let textArr = this.shareInfo.title.split(splitChar);

      let line = "";
      const maxWidth = uni.upx2px(440);
      ctx.textAlign = "left";
      for (let index = 0; index < textArr.length; index++) {
        let testLine = line + textArr[index];
        let lineW = ctx.measureText(testLine).width;
        if (lineW > maxWidth) {
          line += "...";
          break;
        } else {
          line = testLine;
        }
      }
      ctx.fillText(line, padding + uni.upx2px(220), y - uni.upx2px(90));
      ctx.font = `${uni.upx2px(26)}px Arial`;
      ctx.fillText(
        "【长按图片识别二维码】",
        padding + uni.upx2px(208),
        y - uni.upx2px(40)
      );
    },
    loadImage(url) {
      return new Promise((resolve, reject) => {
        let img = canvas.createImage();
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = url;
      });
    },
    toSaveImage() {
      // if (!this.finished) {
      //     uni.showToast({
      //         title: '正在生成图片，稍后再试',
      //         icon: 'none'
      //     })
      //     return
      // }
      uni.canvasToTempFilePath(
        {
          canvas: canvas,
          fileType: "jpg",
          // width: this.canvasW * 2,
          // height: this.canvasH * 2,
          // destWidth: this.canvasW * 2,
          // destHeight: this.canvasH * 2,
          quality: 1,
          success: (res) => {
            this.sharePath = res.tempFilePath;
            this.saveImageToPhotosAlbum(res.tempFilePath);
            console.log(res.tempFilePath);
            let { id, share_title, share_picture, title } = this.shareInfo;
            let shareTitle = share_title || title;
            Share.getShareId({
              id,
              from: "button",
              shareLink: `shop/productDetails/productDetails`,
              shareTitle,
              shareImgUrl: share_picture,
            });
          },
          fail(err) {
            console.log(err);
            uni.showToast({
              icon: "none",
              title: "保存失败",
            });
          },
        },
        this
      );
    },
    saveImageToPhotosAlbum(path) {
      uni.saveImageToPhotosAlbum({
        filePath: path,
        success: () => {
          uni.showToast({
            title: "图片已经保存到相册\n快去分享吧",
            duration: 3000,
            icon: "none",
          });
          this.show = false;
        },
        fail: () => {
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting["scope.writePhotosAlbum"]) {
                uni.showModal({
                  title: "保存失败",
                  content: "请同意访问您的相册",
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting();
                    } else if (res.cancel) {
                      this.show = false;
                    }
                  },
                });
              }
            },
          });
        },
      });
    },
    getImageInfo(url) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: url,
          success: (res) => {
            return resolve(res);
          },
          fail: (err) => {
            console.error(url);
            return reject(err);
          },
        });
      });
    },
  },
};
</script>

<style lang="scss">
.product-share {
  font-size: 32rpx;
  overflow: hidden;
  canvas {
    width: 100%;
    height: 1260rpx;
  }
  .pic-box {
    height: 1260rpx;
    position: relative;
    .img-size-100 {
      display: block;
      width: auto;
      height: 100%;
    }
    .top {
      width: 690rpx;
      position: absolute;
      top: 0rpx;
      left: 0rpx;
      right: 0;
      height: 68rpx;
      background: rgba(0, 0, 0, 0.4);
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffffff;
      font-size: 28rpx;
      .pic {
        flex: 0 0 48rpx;
        height: 48rpx;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 20rpx;
      }
    }
    .bottom {
      width: 100%;
      height: 140rpx;
      position: absolute;
      bottom: 0;
      left: 0;
      background: rgba(0, 0, 0, 0.7);
      .pic-box {
        width: 180rpx;
        height: 180rpx;
        position: absolute;
        bottom: 20rpx;
        left: 50rpx;
      }
      .info-box {
        margin: 20rpx 0 0 260rpx;
        color: #fff;
        font-size: 26rpx;
        width: 455rpx;
        .name {
          height: 40rpx;
          line-height: 40rpx;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 28rpx;
          font-weight: bold;
          margin-bottom: 10rpx;
        }
      }
    }
  }
  .footer-box {
    height: 128rpx;
    .main {
      position: fixed;
      width: 100%;
      height: 128rpx;
      bottom: 0rpx;
      left: 0;
      box-sizing: border-box;
      padding-bottom: 40rpx;
      display: flex;
      justify-content: center;
      background: #fff;
      .btn {
        width: 315rpx;
        height: 88rpx;
        line-height: 88rpx;
        box-sizing: border-box;
        border-radius: 55rpx;
        // border: 1px solid #1772ff;
        background: #2cacff;
        // background: linear-gradient(
        //   270deg,
        //   rgba(44, 172, 255, 1) 0%,
        //   rgba(40, 123, 252, 1) 100%
        // );
        color: #fff;
        font-size: 36rpx;
        font-weight: bold;
        margin: 0 10rpx;
        text-align: center;
        &.direct {
          border: 1px solid #1772ff;
          color: #1772ff;
          background: #fff;
          color: #1772ff;
        }
      }
    }
  }
}
</style>
